<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/";
%>
<html>
<head>
	<base href="<%=basePath%>">
	<meta charset="UTF-8">

	<link href="jquery/bootstrap_3.3.0/css/bootstrap.min.css" type="text/css" rel="stylesheet"/>
	<link href="jquery/bootstrap-datetimepicker-master/css/bootstrap-datetimepicker.min.css" type="text/css"
		  rel="stylesheet"/>

	<script type="text/javascript" src="jquery/jquery-1.11.1-min.js"></script>
	<script type="text/javascript" src="jquery/bootstrap_3.3.0/js/bootstrap.min.js"></script>
	<script type="text/javascript"
			src="jquery/bootstrap-datetimepicker-master/js/bootstrap-datetimepicker.min.js"></script>
	<script type="text/javascript"
			src="jquery/bootstrap-datetimepicker-master/locale/bootstrap-datetimepicker.zh-CN.js"></script>

	<%--引入日历插件所需的.css和.js文件--%>
	<link rel="stylesheet" type="text/css" href="jquery/bootstrap-datetimepicker-master/css/bootstrap-datetimepicker.min.css">
	<script type="text/javascript" src="jquery/bootstrap-datetimepicker-master/js/bootstrap-datetimepicker.js"></script>
	<script type="text/javascript" src="jquery/bootstrap-datetimepicker-master/locale/bootstrap-datetimepicker.zh-CN.js"></script>

	<%-- pagination 插件--%>
	<link rel="stylesheet" type="text/css" href="jquery/bs_pagination-master/css/jquery.bs_pagination.min.css"/>
	<script type="text/javascript" src="jquery/bs_pagination-master/js/jquery.bs_pagination.min.js"></script>
	<script type="text/javascript" src="jquery/bs_pagination-master/localization/en.js"></script>
	<script type="text/javascript">

        function queryAllCustomersByCondition(pn, ps) {
            var name = $.trim($("#condition-name").val());
            var owner = $.trim($("#condition-owner").val());
            var phone = $.trim($("#condition-phone").val());
            var website = $.trim($("#condition-website").val());
            $.ajax({
                url: 'workbench/customer/queryAllCustomers.do',
                type: 'post',
                data: {
                    name: name,
                    owner: owner,
                    phone: phone,
                    website: website,
                    pn: pn,
                    ps: ps
                },
                dataType: 'json',
                success: function (data) {
                    if (data.code == '1') {
                        var htmlStr = "";
                        $.each(data.extend.pageInfo.list, function (index, obj) {
                            htmlStr += "<tr>";
                            htmlStr += "<td><input type=\"checkbox\" value=\"" + obj.id + "\"/></td>";
                            htmlStr += "<td><a style=\"text-decoration: none; cursor: pointer;\" onclick=\"window.location.href=ddetail.jsp\">" + obj.name + "</a></td>";
                            htmlStr += "<td>" + obj.owner + "</td>";
                            htmlStr += "<td>" + (obj.phone == null ? '新建客户暂未填写' : obj.phone) + "</td>";
                            htmlStr += "<td>" + (obj.website == null ? '新建客户暂未填写' : obj.website) + "</td>";
                            htmlStr += "</tr>";
                        });
                        $("#customersTBody").html(htmlStr);

                        // 设置全选按钮不选中
                        $("#checkAllBtn").prop("checked", false);

                        $("#customerNavi").bs_pagination({
                            currentPage: pn, // 当前页号，相当于pageNo
                            rowsPerPage: ps, // 每页显示的条数，即pageSize
                            totalRows: data.extend.pageInfo.total, // 总条数
                            totalPages: data.extend.pageInfo.pages, // 总页数，必填参数

                            visiblePageLinks: 5, // 最多可以显示的卡片数
                            showGoToPage: true, // 是否显示"跳转到"部分，默认true--显示
                            showRowsPerPage: true, // 是否显示"每页显示条数"部分，默认true--显示
                            showRowsInfo: true, // 是否显示记录的信息，默认true--显示

                            // 用户每次切换页号，都自动触发页面切换函数，是插件的提供的内部函数
                            // 每次返回切换页号之后的pageNo和pageSize
                            onChangePage: function (event, pageObj) {
                                queryAllCustomersByCondition(pageObj.currentPage, pageObj.rowsPerPage);
                            }
                        });
                    } else {
                        alert(data.msg);
                    }
                }
            });
        };

		function deleteCustomerAndContacts(isDeleteContacts){
			var deletedList = $("#customersTBody input[type='checkbox']:checked");
			if(deletedList.size() == 0){
				alert("请选择最少一条记录以删除...");
				return;
			}
			var ids = "";
			$.each(deletedList, function (index, obj) {
				ids += "id=" + obj.value + "&";
			});
			ids += "isDeleteContacts=" + isDeleteContacts;
			$.ajax({
				url:'workbench/customer/deleteCustomersSelected.do',
				type:'post',
				data:ids,
				dataType:'json',
				success:function (data) {
					if(data.code == '1'){
						alert("共有" + data.extend.count + "条记录受影响");
						$("#confirmDeleteCustomersWithContacts").modal("hide");
						queryAllCustomersByCondition(1, $("#customerNavi").bs_pagination('getOption', 'rowsPerPage'));
					}else{
						alert(data.msg);
					}
				}
			});
		};

        $(function () {

            queryAllCustomersByCondition(1, 5);

            //定制字段
            $("#definedColumns > li").click(function (e) {
                //防止下拉菜单消失
                e.stopPropagation();
            });

            // 为全选按钮绑定单击事件
            $("#checkAllBtn").click(function () {
                $("#customersTBody input[type='checkbox']").prop("checked", this.checked);
            });

            // 为每一个客户的复选框绑定单击事件
            $("#customersTBody").on("click", "input[type='checkbox']", function () {
                if ($("#customersTBody input[type='checkbox']").size() == $("#customersTBody input[type='checkbox']:checked").size()) $("#checkAllBtn").prop("checked", true);
                else $("#checkAllBtn").prop("checked", false);

            });
            // 为查询按钮绑定单击事件
            $("#queryCustomersBtn").click(function () {
                queryAllCustomersByCondition(1, $("#customerNavi").bs_pagination('getOption', 'rowsPerPage'));
            });

			// 添加日历插件
			$(".timePick").datetimepicker({
				language:'zh-CN', // 语言
				format:'yyyy-mm-dd', // 日期的格式
				minView:'month', // 可以选择的最小视图
				initialDate:new Date(), // 初始化显示的日期
				autoclose:true, // 设置选择完日期或者时间之后，是否自动关闭日历
				todayBtn:true, // 设置是否显示"今天"按钮，默认设置为false
				clearBtn:true // 设置是否显示"清空"按钮，默认是false
			});

			// 为修改按钮绑定单击事件
			$("#editCustomerBtn").click(function (){
				var checkedCustomerList = $("#customersTBody input[type='checkbox']:checked");
				if(checkedCustomerList.size() == 1){
					var id = checkedCustomerList[0].value;
					$.ajax({
						url:'workbench/customer/queryCustomerForEditCustomer.do',
						type:'post',
						dataType:'json',
						data:{
							id:id
						},
						success:function (data){
							if(data.code == 1){
								$("#editCustomerForm")[0].reset();
								$("#customerIdForEdit").val(id);
								$("#edit-customerOwner").val(data.extend.customerForEdit.owner);
								$("#edit-name").val(data.extend.customerForEdit.name);
								$("#edit-phone").val(data.extend.customerForEdit.phone);
								$("#edit-website").val(data.extend.customerForEdit.website);
								$("#edit-description").val(data.extend.customerForEdit.description);
								$("#edit-contactSummary").val(data.extend.customerForEdit.contactSummary);
								$("#edit-nextContactTime").val(data.extend.customerForEdit.nextContactTime);
								$("#edit-address").val(data.extend.customerForEdit.address);
								$("#editCustomerModal").modal("show");
							}else{
								alert(data.msg);
							}
						}
					});
				}else{
					alert("请选择一条记录以编辑...");
				}
			});

			// 为修改模态框中的更新按钮绑定单击事件
			$("#updateEditedCustomerBtn").click(function (){
				var id = $("#customerIdForEdit").val();
				var owner = $("#edit-customerOwner").val();
				var name = $("#edit-name").val();
				var website = $("#edit-website").val();
				var phone = $("#edit-phone").val();
				var description = $("#edit-description").val();
				var contactSummary = $("#edit-contactSummary").val();
				var nextContactTime = $("#edit-nextContactTime").val();
				var address = $("#edit-address").val();
				// 表单验证
				if (owner == null || name == null || name == "" || owner == "") {
					alert("所有者或名称不能为空...");
					return ;
				}
				if (nextContactTime == null || nextContactTime == "") {
					// 使用字符串比较大小代替日期的大小
					alert("下次联系时间不能为空...")
					return ;
				}
				// TODO 判断公司座机是否合法
				// TODO 判断公司网站是否合法
				if(window.confirm("是否要更新该条数据？")){
					$.ajax({
						url:'workbench/customer/updateEditedCustomer.do',
						type:'post',
						dataType:'json',
						data:{
							id:id,
							owner:owner,
							name:name,
							website:website,
							phone:phone,
							description:description,
							contactSummary:contactSummary,
							nextContactTime:nextContactTime,
							address:address
						},
						success:function (data){
							if(data.code == 1){
								alert("更新成功！");
								queryAllCustomersByCondition(1, $("#customerNavi").bs_pagination('getOption', 'rowsPerPage'));
								$("#editCustomerModal").modal("hide");
							}else{
								alert(data.msg);
							}
						}
					});
				}
			});

			// 为创建按钮绑定单击事件
			$("#createCustomerBtn").click(function (){
				$("#createCustomerForm")[0].reset();
				$("#createCustomerModal").modal("show");
			});

			//保存创建的客户信息
			$("#saveCreatedCustomer").click(function (){
				var owner = $("#create-customerOwner").val();
				var name = $.trim($("#create-name").val());
				var website = $.trim($("#create-website").val());
				var phone = $.trim($("#create-phone").val());
				var description = $.trim($("#create-description").val());
				var contactSummary = $.trim($("#create-contactSummary").val());
				var nextContactTime = $("#create-nextContactTime").val();
				var address = $.trim($("#create-address").val());
				// 表单验证
				if (owner == null || name == null || name == "" || owner == "") {
					alert("所有者或名称不能为空...");
					return ;
				}
				if (nextContactTime == null || nextContactTime == "") {
					// 使用字符串比较大小代替日期的大小
					alert("下次联系时间不能为空...")
					return ;
				}
				// TODO 判断公司座机是否合法
				// TODO 判断公司网站是否合法
				if(window.confirm("确认需要保存吗？")){
					$.ajax({
						url:'workbench/customer/saveCreateCustomer.do',
						type:'post',
						dataType:'json',
						data:{
							owner:owner,
							name:name,
							website:website,
							phone:phone,
							description:description,
							contactSummary:contactSummary,
							nextContactTime:nextContactTime,
							address:address
						},
						success:function (data){
							if(data.code == 1){
								alert("保存成功！");
								queryAllCustomersByCondition(1, $("#customerNavi").bs_pagination('getOption', 'rowsPerPage'));
								$("#createCustomerModal").modal("hide");
							}else{
								alert(data.msg);
							}
						}
					});
				}
			});

			//删除所选择的客户信息-> 注意逻辑关系：客户-联系人-交易（商机）
			$("#deleteCustomersBtn").click(function (){
				var deletedList = $("#customersTBody input[type='checkbox']:checked");
				var len = deletedList.size();
				if(len == 0){
					alert("至少选择一个以删除...");
					return;
				}
				$("#deleteCustomersAndContactsH").text("是否要删除这" + deletedList.size() + "条客户记录？");
				$("#confirmDeleteCustomersWithContacts").modal("show");
			});

			//删除客户及其所关联的所有联系人信息
			$("#confirmDeleteFollowContacts").click(function (){
				deleteCustomerAndContacts(1);
			});

			//仅仅删除所选客户信息
			$("#cancelDeleteFollowContacts").click(function (){
				deleteCustomerAndContacts(0);
			});
        });

	</script>
</head>
<body>

	<!-- 创建客户的模态窗口 -->
	<div class="modal fade" id="createCustomerModal" role="dialog">
		<div class="modal-dialog" role="document" style="width: 85%;">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal">
						<span aria-hidden="true">×</span>
					</button>
					<h4 class="modal-title" id="myModalLabel1">创建客户</h4>
				</div>
				<div class="modal-body">
					<form class="form-horizontal" role="form" id="createCustomerForm">
						<div class="form-group">
							<label for="create-customerOwner" class="col-sm-2 control-label">所有者<span style="font-size: 15px; color: red;">*</span></label>
							<div class="col-sm-10" style="width: 300px;">
								<select class="form-control" id="create-customerOwner">
								  <c:forEach items="${users}" var="u">
									  <option value="${u.id}">${u.name}</option>
								  </c:forEach>
								</select>
							</div>
							<label for="create-name" class="col-sm-2 control-label">名称<span style="font-size: 15px; color: red;">*</span></label>
							<div class="col-sm-10" style="width: 300px;">
								<input type="text" class="form-control" id="create-name">
							</div>
						</div>
						
						<div class="form-group">
                            <label for="create-website" class="col-sm-2 control-label">公司网站</label>
                            <div class="col-sm-10" style="width: 300px;">
                                <input type="text" class="form-control" id="create-website">
                            </div>
							<label for="create-phone" class="col-sm-2 control-label">公司座机</label>
							<div class="col-sm-10" style="width: 300px;">
								<input type="text" class="form-control" id="create-phone">
							</div>
						</div>
						<div class="form-group">
							<label for="create-description" class="col-sm-2 control-label">描述</label>
							<div class="col-sm-10" style="width: 81%;">
								<textarea class="form-control" rows="3" id="create-description"></textarea>
							</div>
						</div>
						<div style="height: 1px; width: 103%; background-color: #D5D5D5; left: -13px; position: relative;"></div>

                        <div style="position: relative;top: 15px;">
                            <div class="form-group">
                                <label for="create-contactSummary" class="col-sm-2 control-label">联系纪要</label>
                                <div class="col-sm-10" style="width: 81%;">
                                    <textarea class="form-control" rows="3" id="create-contactSummary"></textarea>
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="create-nextContactTime" class="col-sm-2 control-label">下次联系时间</label>
                                <div class="col-sm-10" style="width: 300px;">
                                    <input type="text" class="form-control timePick" id="create-nextContactTime" readonly>
                                </div>
                            </div>
                        </div>

                        <div style="height: 1px; width: 103%; background-color: #D5D5D5; left: -13px; position: relative; top : 10px;"></div>

                        <div style="position: relative;top: 20px;">
                            <div class="form-group">
                                <label for="create-address" class="col-sm-2 control-label">详细地址</label>
                                <div class="col-sm-10" style="width: 81%;">
                                    <textarea class="form-control" rows="1" id="create-address"></textarea>
                                </div>
                            </div>
                        </div>
					</form>
					
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
					<button type="button" class="btn btn-primary" id="saveCreatedCustomer">保存</button>
				</div>
			</div>
		</div>
	</div>

<%--	确认删除的确认框--%>
	<div class="modal fade" id="confirmDeleteCustomersWithContacts" role="dialog">
		<div class="modal-dialog" role="document" style="width: 40%;">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal">
						<span aria-hidden="true">×</span>
					</button>
					<h4 class="modal-title" id="deleteCustomersAndContactsH"></h4>
				</div>
				<div class="modal-body">
					<h4>是否需要删除这些客户所对应的联系人？</h4>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
					<button type="button" class="btn btn-info" id="cancelDeleteFollowContacts">否(仅仅删除客户)</button>
					<button type="button" class="btn btn-danger" id="confirmDeleteFollowContacts">！！！是(删除客户及其关联的联系人信息)</button>
				</div>
			</div>
		</div>
	</div>

	<!-- 修改客户的模态窗口 -->
	<div class="modal fade" id="editCustomerModal" role="dialog">
		<div class="modal-dialog" role="document" style="width: 85%;">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal">
						<span aria-hidden="true">×</span>
					</button>
					<h4 class="modal-title" id="myModalLabel">修改客户</h4>
				</div>
				<div class="modal-body">
					<form class="form-horizontal" role="form" id="editCustomerForm">
					<input type="hidden" id="customerIdForEdit">
						<div class="form-group">
							<label for="edit-customerOwner" class="col-sm-2 control-label">所有者<span style="font-size: 15px; color: red;">*</span></label>
							<div class="col-sm-10" style="width: 300px;">
								<select class="form-control" id="edit-customerOwner">
									<c:forEach items="${users}" var="u">
										<option value="${u.id}">${u.name}</option>
									</c:forEach>
								</select>
							</div>
							<label for="edit-name" class="col-sm-2 control-label">名称<span style="font-size: 15px; color: red;">*</span></label>
							<div class="col-sm-10" style="width: 300px;">
								<input type="text" class="form-control" id="edit-name" value="动力节点">
							</div>
						</div>
						
						<div class="form-group">
                            <label for="edit-website" class="col-sm-2 control-label">公司网站</label>
                            <div class="col-sm-10" style="width: 300px;">
                                <input type="text" class="form-control" id="edit-website" value="http://www.bjpowernode.com">
                            </div>
							<label for="edit-phone" class="col-sm-2 control-label">公司座机</label>
							<div class="col-sm-10" style="width: 300px;">
								<input type="text" class="form-control" id="edit-phone" value="010-84846003">
							</div>
						</div>
						
						<div class="form-group">
							<label for="edit-description" class="col-sm-2 control-label">描述</label>
							<div class="col-sm-10" style="width: 81%;">
								<textarea class="form-control" rows="3" id="edit-description"></textarea>
							</div>
						</div>
						
						<div style="height: 1px; width: 103%; background-color: #D5D5D5; left: -13px; position: relative;"></div>

                        <div style="position: relative;top: 15px;">
                            <div class="form-group">
                                <label for="edit-contactSummary" class="col-sm-2 control-label">联系纪要</label>
                                <div class="col-sm-10" style="width: 81%;">
                                    <textarea class="form-control" rows="3" id="edit-contactSummary"></textarea>
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="edit-nextContactTime" class="col-sm-2 control-label">下次联系时间</label>
                                <div class="col-sm-10" style="width: 300px;">
                                    <input type="text" class="form-control timePick" id="edit-nextContactTime" readonly>
                                </div>
                            </div>
                        </div>

                        <div style="height: 1px; width: 103%; background-color: #D5D5D5; left: -13px; position: relative; top : 10px;"></div>

                        <div style="position: relative;top: 20px;">
                            <div class="form-group">
                                <label for="create-address" class="col-sm-2 control-label">详细地址</label>
                                <div class="col-sm-10" style="width: 81%;">
                                    <textarea class="form-control" rows="1" id="edit-address"></textarea>
                                </div>
                            </div>
                        </div>
					</form>
					
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
					<button type="button" class="btn btn-primary" id="updateEditedCustomerBtn">更新</button>
				</div>
			</div>
		</div>
	</div>
	
	
	
	
	<div>
		<div style="position: relative; left: 10px; top: -10px;">
			<div class="page-header">
				<h3>客户列表</h3>
			</div>
		</div>
	</div>
	
	<div style="position: relative; top: -20px; left: 0px; width: 100%; height: 100%;">
	
		<div style="width: 100%; position: absolute;top: 5px; left: 10px;">
		
			<div class="btn-toolbar" role="toolbar" style="height: 80px;">
				<form class="form-inline" role="form" style="position: relative;top: 8%; left: 5px;">
				  
				  <div class="form-group">
				    <div class="input-group">
				      <div class="input-group-addon">名称</div>
				      <input class="form-control" type="text" id="condition-name">
				    </div>
				  </div>
				  
				  <div class="form-group">
				    <div class="input-group">
				      <div class="input-group-addon">所有者</div>
				      <input class="form-control" type="text" id="condition-owner">
				    </div>
				  </div>
				  
				  <div class="form-group">
				    <div class="input-group">
				      <div class="input-group-addon">公司座机</div>
				      <input class="form-control" type="text" id="condition-phone">
				    </div>
				  </div>
				  
				  <div class="form-group">
				    <div class="input-group">
				      <div class="input-group-addon">公司网站</div>
				      <input class="form-control" type="text" id="condition-website">
				    </div>
				  </div>
				  
				  <button id="queryCustomersBtn" type="button" class="btn btn-default">查询</button>
				  
				</form>
			</div>
			<div class="btn-toolbar" role="toolbar" style="background-color: #F7F7F7; height: 50px; position: relative;top: 5px;">
				<div class="btn-group" style="position: relative; top: 18%;">
				  <button type="button" class="btn btn-primary" id="createCustomerBtn"><span class="glyphicon glyphicon-plus"></span> 创建</button>
				  <button type="button" class="btn btn-default" id="editCustomerBtn"><span class="glyphicon glyphicon-pencil"></span> 修改</button>
				  <button type="button" class="btn btn-danger" id="deleteCustomersBtn"><span class="glyphicon glyphicon-minus"></span> 删除</button>
				</div>
				
			</div>
			<div style="position: relative;top: 10px;">
				<table class="table table-hover">
					<thead>
						<tr style="color: #B3B3B3;">
							<td><input type="checkbox" id="checkAllBtn"/></td>
							<td>名称</td>
							<td>所有者</td>
							<td>公司座机</td>
							<td>公司网站</td>
						</tr>
					</thead>
					<tbody id="customersTBody">
					</tbody>
				</table>
				<div id="customerNavi"></div>
			</div>
		</div>
		
	</div>
</body>
</html>